package cn.gmph.framework.config.beans;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableTransactionManagement
@Profile("db.jdbc")
public class MysqlDataSource {

    private Logger      logger = Logger.getLogger(this.getClass());

    @Autowired
    private Environment env;

    @Bean(destroyMethod = "close", initMethod = "init")
    public DruidDataSource getDataSource() {
        logger.warn("使用jdbc方式创建数据库连接");
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(this.env.getProperty("jdbc.driverClass"));
        ds.setUrl(this.env.getProperty("jdbc.url"));
        ds.setUsername(this.env.getProperty("jdbc.user"));
        ds.setPassword(this.env.getProperty("jdbc.password"));
        ds.setDefaultAutoCommit(true);
        ds.setTestWhileIdle(true);
        ds.setTestOnBorrow(true);
        ds.setPoolPreparedStatements(true);
        ds.setConnectionProperties("druid.stat.slowSqlMillis=500");
        ds.setValidationQuery("SELECT 1 FROM DUAL");
        return ds;
    }

    @Bean
    public PlatformTransactionManager getPlatformTransactionManager() {
        PlatformTransactionManager txManager = new DataSourceTransactionManager(getDataSource());
        return txManager;
    }

    @Bean(name = "transactionTemplate")
    public TransactionTemplate getTransactionTemplate() {
        return new TransactionTemplate(getPlatformTransactionManager());
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(getDataSource());
        return sessionFactory.getObject();
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate getJdbcTemplate() {
        JdbcTemplate t = new JdbcTemplate();
        t.setDataSource(getDataSource());
        return t;
    }

}
